import Filter from './Filter';
import { useGetDefaultFilterValue } from './Filter/hook';
import { FilterOptionsWithId } from 'common/utils/eq-filter/types';
import { useMemoizedFn, useUpdateEffect } from 'ahooks';
import { Button, Card, Empty, Flex, Popconfirm, Space } from 'antd';
import { cloneDeep, isNil } from 'lodash';
import { useMemo, useRef, useState } from 'react';
import type { FiltersValue } from './types';
import Chart from './Chart';
import { MicroAppWithMemoHistory } from '@umijs/max';
import { getId } from '@/utils';
import { tokenStorage } from '@/utils/storage';
import { SplitCellsOutlined } from '@ant-design/icons';
import SegmentEQ, { SegmentEQRef } from './SegmentEQ';

const formatFilter = (filterParams: FilterParams) => {
  return {
    filterType: filterParams.filterType.replace('_', ''),
    frequency: filterParams.freq,
    q: filterParams.qFactor,
    gain: filterParams.gain,
  } as Omit<FilterOptionsWithId, 'id'>
}

interface FilterProps {
  value?: FiltersValue;
  onChange?: (value: FiltersValue) => void;
  readOnly?: boolean;
}

function Filters(props: FilterProps) {
  const { value, onChange, readOnly } = props;

  const segmentEQRef = useRef<SegmentEQRef>(null);

  const valueRef = useRef(value);

  useUpdateEffect(() => {
    valueRef.current = value;
  }, [value]);

  const defaultFilterValue = useGetDefaultFilterValue();

  const selectedEQ = useMemo(() => {
    if (isNil(value)) {
      return;
    }
    return value.eqs.find(item => item.id === value.currentEQId);
  }, [value]);

  const onAddFilter = useMemoizedFn((addValue?: Omit<FilterOptionsWithId, 'id'>) => {
    if (isNil(value)) {
      return;
    }

    const valueClone = { ...value };
    valueClone.eqs = [...valueClone.eqs, {
      ...(addValue || defaultFilterValue),
      id: getId(),
    }];
    valueClone.currentEQId = valueClone.eqs[valueClone.eqs.length - 1].id;

    onChange?.(valueClone);
  });

  const onRemoveFilter = useMemoizedFn((id?: string) => {
    const currenId = id ?? value?.currentEQId
    if (isNil(value)) {
      return;
    }
    const valueClone = cloneDeep(value);
    valueClone.eqs = valueClone.eqs.filter(item => item.id !== currenId);

    valueClone.currentEQId = valueClone.eqs.length ? valueClone.eqs[valueClone.eqs.length - 1].id : undefined;

    onChange?.(valueClone);
  });

  const onFilterChange = useMemoizedFn((eq: FilterOptionsWithId, id?: string) => {
    if (isNil(value)) {
      return;
    }

    const valueClone = cloneDeep(value);

    const changeId = !isNil(id) ? id : value.currentEQId;
    valueClone.eqs = valueClone.eqs.map(item => item.id === changeId ? eq : item);

    onChange?.(valueClone);
  });

  const onSelectFilter = useMemoizedFn((id: string) => {
    if (isNil(value)) {
      return;
    }
    const valueClone = { ...value, currentEQId: id };
    onChange?.(valueClone);
  });

  const [sourcePoints, setSourcePoints] = useState<number[][]>([]);

  const onGraphPointsChange = useMemoizedFn((points: { x: number; y: number }[]) => {
    setSourcePoints(points.map(item => [item.x, item.y]));
  });

  if (isNil(value)) {
    return <Empty description="请先选择耳机" />;
  }

  return (
    <>
      <Flex gap={16}>
        <div className="flex-1 min-w-0">
          <Chart
            value={value}
            onAddFilter={onAddFilter}
            onFilterChange={onFilterChange}
            onSelectFilter={onSelectFilter}
            onGraphPointsChange={onGraphPointsChange}
            readOnly={readOnly}
          />
        </div>

        <div className={`w-[${readOnly ? '400px' : '400px'}]`} style={{ maxHeight: '600px' }}>
          <Space className='mb-[8px] w-full justify-center'>
            <SegmentEQ sourcePoints={sourcePoints}ref={segmentEQRef} onConfirm={(filters)=>{
              const finalFilters = filters.map(item=>{
                return {
                  ...item,
                  id: Math.random().toString(),
                }
              }) as FilterOptionsWithId[]

             const valueClone = cloneDeep(value);

              onChange?.({
                ...valueClone,
                eqs: finalFilters,
                currentEQId: finalFilters[finalFilters.length - 1].id,
              });
            }}>
              <Button icon={
                <SplitCellsOutlined />
              } size='small' ghost type='primary'>
                调音融合（多耳机拼接）
              </Button>
            </SegmentEQ>
          </Space>
          {!selectedEQ ? (
            readOnly ? <Empty description="暂无采样点" /> : <div className="text-center h-[238px]">
              请先
              <a type="text" className="p-1" onClick={() => {
                onAddFilter();
              }}>
                添加
              </a>
              一个采样点
            </div>
          ) : (
            <>
              <Card
                classNames={{
                  body: 'p-3',
                }}
              >
                <Filter value={selectedEQ} onChange={onFilterChange} readOnly={readOnly} />
                {
                  !readOnly && <Popconfirm title="确定删除吗？" onConfirm={() => {
                    onRemoveFilter();
                  }}>
                    <Button block danger>
                      删除
                    </Button>
                  </Popconfirm>
                }
              </Card>
            </>
          )}
          {
            !readOnly && value?.freqToDB && <MicroAppWithMemoHistory
              className='h-[570px] mt-[4px]'
              settings={{
                sandbox: {
                  experimentalStyleIsolation: true,
                },
              }}
              name="ai-assistant"
              entry='https://ai.huihifi.com/aituning'
              basename="/"
              userToken={tokenStorage.get()}
              getSharedData={() => {
                const param = {
                  originalDataSource: valueRef.current?.freqToDB.dataSet,
                  appliedFilters: valueRef.current?.eqs,
                };
                console.log('getSharedData return', param)
                return param;
              }}
              debugSettings={{
                enabled: false,        // 是否启用调试信息面板
                defaultVisible: false // 调试面板默认是否可见
              }}
              callbacks={{
                addFilterFromLLM: (filterParams: FilterParams) => {
                  // 添加滤波器逻辑
                  console.log('添加滤波器:', filterParams);
                  // 实现滤波器添加的逻辑
                  onAddFilter(formatFilter(filterParams));
                },
                editFilterFromLLM: (filterId: string, filterParams: FilterParams) => {
                  // 编辑滤波器逻辑
                  console.log('编辑滤波器:', filterId, filterParams);
                  // 实现滤波器编辑的逻辑
                  onFilterChange({
                    ...formatFilter(filterParams),
                    id: filterId,
                  }, filterId)
                  return true; // 返回操作是否成功
                },
                deleteFilterFromLLM: (filterId: string) => {
                  // 删除滤波器逻辑
                  console.log('删除滤波器:', filterId);
                  // 实现滤波器删除的逻辑
                  onRemoveFilter(filterId);
                  return true; // 返回操作是否成功
                },
                coverSegmentFromLLM: (data: {
                  data_list: {
                    frequency_range: [number, number];
                    name: string;
                    uuid: string;
                    dataGroup: string;
                  }[];
                }) => {
                  // 分段EQ逻辑
                  console.log('分段EQ添加:', data);
                  // 实现分段EQ的逻辑
                  segmentEQRef.current?.open({
                    segmentList: data.data_list.map(item => {
                      return {
                        id: item.uuid,
                        range: item.frequency_range,
                        target: {
                          evaluationUuid: item.uuid,
                          dataGroup: item.dataGroup,
                        },
                      }
                    }),
                  });
                },
              }}
            />
          }
        </div>
      </Flex>
    </>
  );
}

export default Filters;

interface FilterParams {
  filterType: 'peaking' | 'low_shelf' | 'high_shelf' | 'lowpass' | 'highpass';
  freq: number;
  gain?: number;
  qFactor: number;
}
